package com.youxuit.youxu.kecheng.CASandAtomic;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * javabasic2021
 * <p>
 * 自定义线程工厂
 * 自定义线程相关设置，方便后续问题定位
 *
 * @author ZhenXu
 * @date 2023-12-20 21:34
 **/
public class MyCustomThreadFactory implements ThreadFactory {

    /**
     * 线程编号，从1开始
     * 避免并发问题，因而使用原子操作类
     */
    private final AtomicInteger threadNum = new AtomicInteger(1);

    @Override
    public Thread newThread(Runnable r) {
        //每次获取一个线程便将线程编号自增1
        String threadName = "customThread-Z" + threadNum.getAndIncrement();

        System.out.println("创建线程：" + threadName);

        return new Thread(r, threadName);
    }
}
